package lesson5.example3.transformer;

import java.security.ProtectionDomain;

import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LineNumberAttribute;

public class ReplaceTransformer extends AbstractTransformer {
	
	String methodName;
	Integer lineNumber;
	String code;

	public ReplaceTransformer(String fullClassName, String methodName, Integer lineNumber, String code) {
		super(fullClassName);
		this.methodName = methodName;
		this.lineNumber = lineNumber;
		this.code = code;
	}

    public byte[] doTransform(
    		ClassLoader loader, 
    		String className, 
    		Class<?> classBeingRedefined,
            ProtectionDomain protectionDomain, 
            byte[] classfileBuffer, 
            CtClass cc) throws Exception {
    	
        CtMethod m = cc.getDeclaredMethod(methodName);
        clearline(m);
        m.insertAt(lineNumber, code);
        return cc.toBytecode();
    }

    protected void clearline(CtMethod m) throws Exception {
        CodeAttribute codeAttribute = m.getMethodInfo().getCodeAttribute();
        LineNumberAttribute lineNumberAttribute = (LineNumberAttribute) codeAttribute.getAttribute(LineNumberAttribute.tag);
        int startPc = lineNumberAttribute.toStartPc(lineNumber);
        int endPc = lineNumberAttribute.toStartPc(lineNumber + 1);
        byte[] code = codeAttribute.getCode();
        for (int i = startPc; i < endPc; i++) {
            code[i] = CodeAttribute.NOP;
        }
    }
}